﻿using System.Linq;
using Android;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Provider;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.Core.App;
using AndroidX.Fragment.App;
using Google.Android.Material.FloatingActionButton;
using Java.IO;

namespace AppExample
{
    public class CameraFragment : Fragment
    {
        const int IMAGE_CAPTURE = 1;
        static File file;

        ImageView _imgView;

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Create your fragment here
            if (file == null)
            {
                file = new File(Context.GetExternalFilesDir(Environment.DirectoryPictures), "tmp.jpg");
            }
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var view = inflater.Inflate(Resource.Layout.fragment_camera, container, false);
            _imgView = view.FindViewById<ImageView>(Resource.Id.imgView);

            var fab = view.FindViewById<FloatingActionButton>(Resource.Id.fab);
            fab.Click += (s, e) =>
            {
                // 处理权限申请
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    var requiredPermissions = new[] { Manifest.Permission.Camera, Manifest.Permission.WriteExternalStorage };
                    var count = requiredPermissions.Where(r => ActivityCompat.CheckSelfPermission(Context, r) != Permission.Granted)
                        .Count();

                    if (count > 0)
                    {
                        RequestPermissions(requiredPermissions, 1);
                    }
                    else
                    {
                        var intent = new Intent(MediaStore.ActionImageCapture);
                        intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(file));
                        StartActivityForResult(intent, IMAGE_CAPTURE);
                    }
                }
            };

            return view;
        }

        public override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            if (requestCode == IMAGE_CAPTURE && resultCode == -1)
            {
                _imgView.SetImageURI(Android.Net.Uri.FromFile(file));
            }
            base.OnActivityResult(requestCode, resultCode, data);
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}